let handler = require("../data_model_service_handler")
let ddl_handler = require("./ddl_handler")
let db = require("../../db/db")

handler.set_db(db);
ddl_handler.set_db(db);

let add = async function (data, login_info, req, res) {
    let rst = await handler.add(data, login_info, req, res);
    await ddl_handler.add_data_funcs(rst.results.insertId, login_info, req, res);
    await ddl_handler.ddl_add_table(data.rows[0].tablename, JSON.parse(data.rows[0].config));
    return rst;
}
let del = async function (data, login_info, req, res) {
    let rst = await handler.del(data, login_info, req, res);
    let id = data.id;
    await ddl_handler.del_data_funcs(id, login_info, req, res);
    let result = await db.query("select * from sys_datamodel where id=?", [id]);
    let row = result.rows[0];
    await ddl_handler.ddl_drop_table(row.tablename);
    return rst;
}
let update = async function (data, login_info, req, res) {
    await handler.update(data, login_info, req, res);    
    let result = await ddl_handler.ddl_change_table(data);
    return result;
}

module.exports = { add, update, del }